<template>
  <div class="container">
    <a-divider orientation="left" orientation-margin="0px">工具箱敏感数据识别</a-divider>
    <a-row class="toolbox-left">
      <a-col :span="24" v-if="toolboxcom">
        <a-form :model="formState" name="validate_other" v-bind="formItemLayout" @finish-failed="onFinishFailed" @finish="onFinish" :rules="formRules">
          <a-form-item style="font-size: 24px">
            <a-form-item name="dragger" noStyle>
              <a-upload-dragger
                v-model:fileList="fileList"
                name="file"
                :multiple="false"
                :action="originalAction"
                :beforeUpload="beforeUpload"
                :data="(file) => ({ fileName: file.name, fileSize: file.size })"
                :headers="uploadHeaders"
                @change="handleChange"
                @drop="handleDrop"
              >
                <p class="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p class="ant-upload-text">点击或将文件拖拽到这里上传</p>
                <p class="ant-upload-hint" style="padding: 10px 14px 0">支持对以下文件类型进行敏感数据发现：DMP、TXT、CSV、XLSX、XLS、DEL、DOC、DOCX、PPT、PPTX、PDF、DCM、E。</p>
              </a-upload-dragger>
            </a-form-item>
          </a-form-item>
          <a-divider orientation="left" orientation-margin="0px">选择扫描规则</a-divider>
          <a-form-item name="group">
            <a-cascader v-model:value="formState.datadesensitization" :options="options" :placeholder="placeholder" size="large" />
          </a-form-item>
          <a-form-item style="text-align: center">
            <a-button type="primary" htmlType="submit" size="large" :disabled="isSubmitting">敏感数据识别</a-button>
          </a-form-item>
        </a-form>
      </a-col>

      <a-col :span="24" class="toolboxbut" v-if="toolboxbut">
        <!--正在处理文件-->
        <a-space v-if="loading" class="loading">
          <a-spin tip="文件正在处理中..." size="large" />
        </a-space>

        <!--展示表格-->

        <div id="components-table-demo-size" v-if="dowbut">
          <a-table :columns="columns" :data-source="data" size="small" />
        </div>
      </a-col>

      <a-col :span="24" class="toolboxend" v-if="toolboxend">
        <a-button size="large" @click="goToToolbox">返回工具箱</a-button>
      </a-col>
    </a-row>

    <a-row>
      <a-col :span="24" class="zi_bottom">
        <p>工具对上传的文件进行敏感数据检测，使用步骤如下：</p>
        <p>（1）上传文件</p>
        <p>（2）点击【敏感数据识别】启动检测</p>
        <p>（3）处理完成后显示识别结果</p>
      </a-col>
    </a-row>
  </div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue'
import { UploadOutlined, InboxOutlined, DownloadOutlined, BookFilled } from '@ant-design/icons-vue'
import type { UploadChangeParam, UploadFile } from 'ant-design-vue'
import { message, CascaderProps } from 'ant-design-vue'
import { useUserStoreWithOut } from '@/stores/modules/user'
import { dmsMaskCenterApi } from '@/api/dms-mask-center'
import { GetDownloadList } from '@/api/dms-mask-center/type'
import { http } from '@/utils/http'
import type { ApiResult } from '@/types/app'
import type { SensitiveItem } from '@/types'
import { useRoute } from 'vue-router'
const fileList = ref<UploadFile[]>([])
const subTitle = ref('')
const namekey = ref('')
const wataskid = ref('')
const parentPath = ref('')
const loading = ref(false)
const dowbut = ref(false)
const isSubmitting = ref(false)
const absPath = ref('')
const toolboxcom = ref(true)
const toolboxbut = ref(false)
const toolboxend = ref(false)
// 表格标题
const columns = [
  { title: '文件名', dataIndex: 'fileName', width: '30%' },
  { title: '数据类型', dataIndex: 'dataTypeMatch', width: '20%' },
  { title: '数据分类', dataIndex: 'classifyName', width: '35%' },
  { title: '数据分级', dataIndex: 'levelName', width: '15%' }
]
// 定义表格数据类型接口，与后端返回字段匹配
interface TableData {
  key: string
  fileName: string
  dataTypeNames: string
  dataClassifyName: string
  dataLevelName: string
}
// 表格数据
const data = ref<TableData[]>([])

const formRules = {
  // 文件上传校验：必须上传文件
  file: [
    {
      required: true,
      message: '请上传文件',
      trigger: ['change', 'submit']
    }
  ]
}
const originalAction = import.meta.env.VITE_GLOB_API_URL + 'dms-mask-center/api/v1/resource/uploadOssFile'

const handleChange = (info: UploadChangeParam) => {
  const status = info.file.status
  if (status === 'done') {
    message.success(`文件上传成功！`)
    const response = info.file.response
    subTitle.value = info.file.name
    console.log('后端返回内容：', response)
    namekey.value = response.data.key
    parentPath.value = response.data.parentPath
  } else if (status === 'error') {
    message.error(`文件上传失败！`)
  }
}
const beforeUpload = (file: UploadFile) => {
  // 检查当前文件列表长度，若已有文件则阻止上传
  if (fileList.value.length >= 1) {
    message.warning('只能上传一个文件，请先删除已上传的文件！')
    return false // 阻止上传
  }
  return true
}
function handleDrop(e: DragEvent) {
  console.log(e)
}

//请求头内容
const uploadHeaders = {
  Authorization: `Bearer ${useUserStoreWithOut().getToken()}` // 示例：添加身份令牌
}
const formState = reactive<Record<string, any>>({
  group: '' // 必须添加，与输入框绑定对应
})
//提交执行
const onFinish = (values: any) => {
  if (fileList.value.length <= 0) {
    message.error('请上传需要识别的文件！')
    return false
  }
  //按钮禁用
  isSubmitting.value = true
  // 获取各时间部分并补零
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0') // 月份从0开始，需+1
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const formattedTime = `${year}${month}${day}${hours}${minutes}`

  const requestData = {
    taskMode: 'QUICK',
    id: null,
    name: '工具箱数据识别' + formattedTime,
    executeType: 'IMMEDIATE',
    triggerContent: null,
    repositoryIdList: ['1', null],
    findStrategy: Array.isArray(formState.datadesensitization) ? formState.datadesensitization[0] : formState.datadesensitization,
    dbResourceList: [],
    fileResourceList: [
      {
        resourceId: import.meta.env.VITE_GLOB_SRID,
        scanDir: '/' + parentPath.value,
        exportPath: '/'
      }
    ],
    receiveEmailUserId: null,
    customEmail: null,
    taskExecutorId: 'DSMP',
    fileEncoding: 'UTF-8'
  }

  // 2. 深拷贝数据（避免原对象被引用修改）
  const dataWithNulls = JSON.parse(JSON.stringify(requestData))

  // 3. 手动序列化数据为JSON字符串（强制保留null）
  const serializedData = JSON.stringify(dataWithNulls, (key, value) => {
    // 明确保留null值，即使是空数组或对象
    if (value === null) return null
    // 保留空数组（如果需要）
    if (Array.isArray(value) && value.length === 0) return []
    return value
  })
  //测试表格内容
  // dmsMaskCenterApi.postSensitiveline({
  //   data: {
  //     "taskId":'8001bf572f5c41a09c9fc07dfa0ef45e',
  //     "repositoryId":"1"
  //   },
  // }).then(response => {
  //   loading.value=false;
  //   dowbut.value=true;
  //   isSubmitting.value = false;
  //   const responseData = response.data.list || response.data;
  //   data.value = (Array.isArray(responseData) ? responseData : []).map((item, index) => ({
  //     ...item,
  //     key: index.toString()
  //   }));
  // })
  // .catch(error => {
  //   isSubmitting.value = false;
  // });

  dmsMaskCenterApi
    .postSensitive({
      data: serializedData,
      headers: {
        'Content-Type': 'application/json' // 必须指定JSON类型
      },
      // 禁用自动转换（防止库再次处理数据）
      transformRequest: [(data) => data] // 直接返回原始数据
    })
    .then((response) => {
      loading.value = false
      dowbut.value = false
      loading.value = true
      toolboxcom.value = false
      toolboxbut.value = true
      toolboxend.value = true
      //获取的任务ID
      console.log(response.data.id)
      // http.put<ApiResult<any>>({ url: '/dms-mask-center/api/v1/task/submit/'+response.data.id});
      wataskid.value = response.data.id

      // 定义定时器变量（用于后续清除）
      let queryInterval = null

      // 开始定时查询（3秒一次）
      queryInterval = setInterval(() => {
        // 获取表格信息
        dmsMaskCenterApi
          .postSensitiveline({
            data: {
              fileNamePath: parentPath.value,
              assetCategory: 'ENTITY',
              repositoryId: '1',
              resGroupId: '1'
            }
          })
          .then((response) => {
            // 解析接口返回数据
            const responseData = response.data.list || response.data
            const isDataValid = Array.isArray(responseData) && responseData.length > 0

            // 如果有有效数据，停止循环并处理数据
            if (isDataValid) {
              clearInterval(queryInterval) // 清除定时器，终止循环
              loading.value = false
              dowbut.value = true
              isSubmitting.value = false
              // 处理数据（添加key）
              data.value = responseData.map((item, index) => ({
                ...item,
                key: index.toString()
              }))
            } else {
              // 无有效数据，继续循环查询（3秒后再次执行）
              console.log('未获取到数据，继续查询...')
            }
          })
          .catch((error) => {
            console.error('查询失败：', error)
            // 可选：失败时是否停止循环？这里选择继续查询
          })
      }, 5000) // 3000毫秒 = 3秒，每3秒执行一次
    })
    .catch((error) => {
      // message.warning('提交失败！');
      isSubmitting.value = false
    })

  console.log('Success:', values)
}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo)
}

//提交加水印
const postwatermark = () => {}
//请选择扫描规则
const options = ref<CascaderProps['options']>([])
const placeholder = ref<string>('请选择扫描规则')
const datadesensitization = ref('')

onMounted(async () => {
  try {
    // 调用接口获取数据
    const response = await dmsMaskCenterApi.getSensitive()
    const rawData: SensitiveItem[] = response.data // 假设数据在 response.data 中

    if (rawData && rawData.length > 0) {
      // 1. 映射数据为级联选择器需要的格式（value + label）
      options.value = rawData.map((item) => ({
        value: item.id,
        label: item.name,
        // 处理子级（如果有）
        children: item.children?.map((child) => ({
          value: child.id,
          label: child.name
        }))
      }))

      // 2. 将第一个数据的 label 设为默认占位符
      placeholder.value = options.value[0].label
      formState.datadesensitization = [options.value[0].value]
    } else {
      // 没有数据时显示默认提示
      placeholder.value = '暂无脱敏规则数据'
    }
  } catch (error) {
    message.error('获取数据失败，请重试')
  }
})

const router = useRouter()
const goToToolbox = () => {
  // 使用 router.push 跳转到指定路由
  location.reload()
}
</script>

<style scoped>
.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
.form-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}
.ant-form-item .ant-form-item-label > label {
  font-size: 16px;
}
.ant-upload-wrapper .ant-upload-drag {
  padding: 7vh 0;
}
:where(.css-dev-only-do-not-override-10npqub).ant-upload-wrapper .ant-upload-drag p.ant-upload-drag-icon .anticon {
  font-size: 7rem;
}
:where(.css-dev-only-do-not-override-10npqub).ant-upload-wrapper .ant-upload-drag p.ant-upload-text {
  color: #1890ff;
}
.container .zi_bottom {
  border-top: solid 10px #eef4ff;
  padding: 1rem 0;
}
.ant-result .ant-result-title {
  color: #1890ff;
  font-size: 18px;
}
.container .toolboxbut {
  border: 1px dashed #d9d9d9;
  text-align: center;
  min-height: 42vh;
}
.container .toolboxbut .loading {
  padding: 18vh;
}
.container .toolboxend {
  text-align: center;
  margin: 28px 0;
}
.ant-result .ant-result-extra {
  margin-top: 12px;
}
.zi_bottom h1 {
  font-size: 16px;
}
.zi_bottom p {
  color: #999;
}
</style>
